﻿using System;
using System.Collections.Generic;
using System.Text;
using ET;

namespace Marx
{
    [ObjectSystem]
    public class PlayerPrefsAwakeSystem : AwakeSystem<PlayerPrefsComponent>
    {
        public override void Awake(PlayerPrefsComponent self)
        {
            self.Awake();
        }
    }

    public class PlayerPrefsComponent : Entity, IAwake
    {
        public static PlayerPrefsComponent Instance { get; private set; }

        public int ServerIndex { get; private set; }
        public int ServerPort { get; private set; }
        public string ServerIP { get; private set; }
        public string Account { get; private set; }
        public string Password { get; private set; }

        private const string key_server_index_ = "server_index";
        private const string key_server_ip_ = "server_ip";
        private const string key_server_port_ = "server_port";
        private const string key_account_ = "account";
        private const string key_password_ = "password";

        public void Awake()
        {
            Instance = this;
            Load();
        }

        private void Load()
        {
            ServerIndex = UnityEngine.PlayerPrefs.GetInt(key_server_index_, 0);

            ServerIP = UnityEngine.PlayerPrefs.GetString(key_server_ip_);
            if (string.IsNullOrEmpty(ServerIP))
            {
                ServerIP = "127.0.0.1";
            }
            ServerPort = UnityEngine.PlayerPrefs.GetInt(key_server_port_, 20001);

            Account = UnityEngine.PlayerPrefs.GetString(key_account_);
            if (string.IsNullOrEmpty(Account))
            {
                Account = Guid.NewGuid().ToString();
                UnityEngine.PlayerPrefs.SetString(key_account_, Account);
            }

            Password = UnityEngine.PlayerPrefs.GetString(key_password_);
            if (string.IsNullOrEmpty(Password))
            {
                Password = "111";
                UnityEngine.PlayerPrefs.SetString(key_password_, Password);
            }
        }

        public void SetServerIndex(int index)
        {
            ServerIndex = index;
            UnityEngine.PlayerPrefs.SetInt(key_server_index_, index);
        }

        public void SetServer(string ip, int port)
        {
            ServerIP = ip;
            ServerPort = port;
            UnityEngine.PlayerPrefs.SetString(key_server_ip_, ip);
            UnityEngine.PlayerPrefs.SetInt(key_server_port_, port);
        }

        public void SetAccount(string account)
        {
            Account = account;
            UnityEngine.PlayerPrefs.SetString(key_account_, account);
        }

        public void SetPassword(string password)
        {
            Password = password;
            UnityEngine.PlayerPrefs.SetString(key_password_, password);
        }
    }
}
